package com.haoran.dwz.security;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationHeader {

	private Logger logger = LoggerFactory.getLogger(getClass());
	public static final String HEAD_KEY_CONTENT_TYPE = "Content-Type";
	public static final String HEAD_KEY_KYE = "kye";
	public static final String HEAD_KEY_ACCESS_TOKEN = "access-token";

	@Value("${security.header.contentType:application/json;charset=UTF-8}")
	private String contentType;
	@Value("${security.header.kye:10005}")
	private String kye;
	@Value("${security.header.accesskey:A63F2C3FF29A606979AE9D25F737B342}")
	private String salt;

	public Map<String, String> create(String json) {
		Map<String, String> headerParam = new HashMap<>();
		headerParam.put(HEAD_KEY_CONTENT_TYPE, contentType);
		headerParam.put(HEAD_KEY_KYE, kye);
		ResponseEntity<Map<String, String>> md5Result = AccessTokenGenerater.getMD5Result(salt, json);
		Map<String, String> body = md5Result.getBody();
		if (!StringUtils.isBlank(body.get("md5Json"))) {
			logger.debug(body.get("sortJson"));
			headerParam.put(HEAD_KEY_ACCESS_TOKEN, body.get("md5Json"));
			return headerParam;
		} else {
			throw new RuntimeException("生成失败: " + body.get("error"));
		}
	}
}
